<?php

namespace app\service\payment\gateway;

use app\libs\PayoneerSDK\Action\Payment;
use app\libs\PayoneerSDK\Builder\PaymentBuilder;
use app\model\Notify;
use app\model\Orders;
use think\helper\Arr;
use think\Request;

class PayoneerService  implements PaymentInterface
{

    public function placeOrder(Orders $order, Request $request)
    {
        $builder = new PaymentBuilder($order);
        $client = new Payment($order->payment);
        $result = $client->createPayment($builder);
        Notify::saveParams($order->id,['params'=>$builder->toArray(),'result'=>$result],Notify::TYPE_PLACE_ORDER,$order->pay_method);
        $this->checkResult($result);
        //是否保存
        $transaction_id = Arr::get($result,'identification.shortId','');
        $paypal_order_id = Arr::get($result,'identification.longId','');
        $order->trade_no = $transaction_id;
        $order->order_no = $paypal_order_id;
        $order->pay_status = Arr::get($result,'returnCode.name','');
        $order->save();
        //执行支付
        $links = Arr::get($result,'redirect',[]);
        if(empty($links)) throw new \Exception('A create order fail');
        $paypal_approve_url = Arr::get($links,'url', '');
        $pay_result = $result;
        return compact('transaction_id', 'paypal_approve_url','pay_result');

    }

    protected function checkResult($result){
        $returnCode = $result['returnCode'] ?? [];
        if (empty($returnCode)) throw new \Exception($result['resultInfo']);
        $isOk = $returnCode['name'] ?? 'err';
        if ($isOk != 'OK') throw new \Exception($result['resultInfo']);
    }

    public function confirmPayment()
    {
        return [];
    }

    public function repurchase(Orders $order, Request $request){
        //todo
        return false;
    }
}